<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { roleStore } from '@/stores/role'
import { headersStore } from '@/stores/apiHeader'
import { useRouter } from 'vue-router'
import { t, langNameObj } from '@/i18n'
import { initLoginBg } from '@/Utils/sky'
import Api from '@/api'
import { removeOrbitControls } from '@/Utils/global'

const router = useRouter()
const userStore = useUserStore()
const theRoleStore = roleStore()
const theHeadersStore = headersStore()
// 是否为开发环境
const isDev = process.env.NODE_ENV === 'development'

// 登录相关对象,包括用户名,密码,验证码
const loginForm = reactive({
  userName: '',
  password: '',
  code: '',
  key: '',
})

// 验证码图片
const imageCode = ref('')
const imageCodeLoading = ref(false)

const currentLangCode = ref(theHeadersStore.language_id || 'zh-cn')
const currentLangName = ref(langNameObj[currentLangCode.value])

onMounted(() => {
  // 找到 class为orbit-controls的dom元素，然后删除该元素
  removeOrbitControls()
  // 加载星空背景
  initLoginBg()
  // 获取验证码的key
  loginForm.key = randomNum(24, 16)
  // 获取验证码
  getCodeImage()
})

// 获取验证码
const getCodeImage = () => {
  imageCodeLoading.value = true
  loginForm.code = ''
  Api.getCaptcha(loginForm.key)
    .then((response) => {
      const res = response
      if (res.byteLength <= 100) {
        ElMessage({
          message: t('meeting_front_getcodefailed'),
          type: 'error',
        })
        return false
      }
      return (
        'data:image/png;base64,' +
        btoa(
          new Uint8Array(res).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ''
          )
        )
      )
    })
    .then((res) => {
      imageCode.value = res
    })
    .catch((e) => {
      if (e.toString().indexOf('429') !== -1) {
        // 次数过多
        ElMessage({
          message: t('meeting_front_getcodefailed'),
          type: 'error',
        })
      } else {
        ElMessage({
          message: t('meeting_front_getcodefailed'),
          type: 'error',
        })
      }
    })
    .finally(() => {
      imageCodeLoading.value = false
    })
}
// 登录
const submitLoading = ref(false)
const onSubmit = () => {
  // 请填写账号
  if (!loginForm.userName) {
    ElMessage({
      message: t('bi_login_enteraccount'),
      type: 'error',
    })
    return
  }
  // 如果是开发环境,则默认填写验证码
  if (isDev) {
    loginForm.code = '2024'
  }
  // 请填写密码
  if (!loginForm.password) {
    ElMessage({
      message: t('bi_login_enterpassword'),
      type: 'error',
    })
    return
  }
  if (process.env.NODE_ENV === 'development' && loginForm.code === '') {
    loginForm.code = '2024'
  }
  // 请填写验证码
  if (!loginForm.code) {
    ElMessage({
      message: t('meeting_front_fillintheverificationcode'),
      type: 'error',
    })
    return
  }

  submitLoading.value = true

  Api.login(loginForm)
    .then((res: any) => {
      if (res.code == 0) {
        // 获取token
        const token = res?.data?.kmToken || ''
        if (!token) {
          ElMessage({
            message: t('meeting_backend_operationfailed'),
            type: 'error',
          })
          getCodeImage()
          return ''
        }
        userStore.setToken(token)
        // 存入用户信息
        userStore.setUserInfo(res.data)
        // 存入角色信息
        //后端那边 1世界 2是区域 3是国家
        //前端是0: 普通用户 1: 国家 2: 区域 3: 世界
        let role1 = parseInt(res.data.businessLevel) || 0 // 业绩等级
        let role2 = parseInt(res.data.supplyLevel) || 0 // 供应链等级
        let role3 = parseInt(res.data.financeLevel) || 0 // 财务等级
        let role4 = parseInt(res.data.humanLevel) || 0 // 财务等级
        theRoleStore.setRole(role1, role2, role3, role4) // 存入角色信息
        // 跳转到首页
        router.push('/')
      } else {
        ElMessage({
          message: res.msg || t('meeting_backend_operationfailed'),
          type: 'error',
        })
        getCodeImage()
      }
    })
    .catch((e) => {
      ElMessage({
        message: e.msg || t('meeting_backend_operationfailed'),
        type: 'error',
      })
      getCodeImage()
    })
    .finally(() => {
      // 多loading1.5秒,防止成功后,页面加载太慢了..
      setTimeout(() => {
        submitLoading.value = false
      }, 1500)
    })
}

const handleLangChange = async (langCode: string) => {
  theHeadersStore.setLanguageId(langCode)
  location.reload()
}

const randomNum = (len, radix) => {
  const chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  radix = radix || chars.length

  if (len) {
    // Compact form
    for (let i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    let r

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (let i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('') + new Date().getTime()
}
</script>

<template>
  <div class="login-body">
    <canvas id="sky" />
    <header>
      <img class="logo" src="@/assets/images/login/tiens.png" />
      <div>{{ $t('bi_login_datacockpit') }}</div>
      <div class="i18n-div">
        <img src="@/assets/images/login/header-i18n.png" alt="i18n" />
        <el-dropdown trigger="click">
          <span class="el-dropdown-lang"> {{ currentLangName }} </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(langName, langCode) in langNameObj"
                @click="handleLangChange(langCode)"
                :disabled="langCode === currentLangCode"
                ><span style="user-select: none">{{
                  langName
                }}</span></el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>
    <div class="middle-bg"></div>
    <div class="login-div">
      <form>
        <div class="title">{{ $t('bi_login_kmlogin') }}</div>
        <div class="account-input">
          <img src="@/assets/images/login/user_icon.png" />
          <div class="line"></div>
          <el-input
            type="text"
            :maxlength="30"
            v-model="loginForm.userName"
            autocomplete="off"
            @blur="
              loginForm.userName = (
                $event.target as HTMLInputElement
              ).value.trim()
            "
          ></el-input>
        </div>
        <div class="password-input">
          <img src="@/assets/images/login/password_icon.png" />
          <div class="line"></div>
          <el-input
            type="password"
            :maxlength="30"
            v-model="loginForm.password"
            autocomplete="new-password"
            @blur="
              loginForm.password = (
                $event.target as HTMLInputElement
              ).value.trim()
            "
          ></el-input>
        </div>
        <!-- 验证码 -->
        <div class="validate-input" v-if="!isDev">
          <el-input
            type="text"
            :maxlength="6"
            v-model="loginForm.code"
            :placeholder="$t('bi_login_vericode')"
            autocomplete="off"
            @blur="
              loginForm.code = ($event.target as HTMLInputElement).value.trim()
            "
          />
          <div class="img-div" v-loading="imageCodeLoading">
            <img :src="imageCode" @click="getCodeImage" />
          </div>
        </div>
        <el-button type="primary" @click="onSubmit" :loading="submitLoading">{{
          $t('bi_login_login')
        }}</el-button>
      </form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login-body {
  background: #030e3a;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

header {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 11;
  width: 100vw;
  height: 75px;
  background: url('@/assets/images/login/header_bg.png') no-repeat center center;
  background-size: cover;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  // 禁止复制文字
  user-select: none;
  font-size: 25px;

  .logo {
    height: 29px;
    margin-right: 20px;
  }

  .i18n-div {
    position: absolute;
    width: 120px;
    right: 30px;
    top: 20px;
    display: flex;
    align-items: center;
    justify-content: top;
    flex-wrap: nowrap;

    img {
      width: 35px;
      height: 35px;
      margin-right: 5px;
    }

    .el-dropdown-lang {
      color: #fff;
      cursor: pointer;
      font-size: 16px;
      white-space: nowrap;
      user-select: none;
    }
  }
}

:deep(.el-dropdown-menu__item) {
  font-size: 16px;
  height: 40px;
  width: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
}

#sky {
  position: absolute;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 11;
  background-color: #fff;
  opacity: 0.3;
}

.middle-bg {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 100vw;
  height: 100vh;
  background: #030e3a url('@/assets/images/login/middle_bg.png') no-repeat
    center top;
  background-size: contain;
  overflow: hidden;
  z-index: 10;
}

.login-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 621px;
  height: 460px;
  background: url('@/assets/images/login/login_div.png') no-repeat center center;
  background-size: cover;
  overflow: hidden;
  z-index: 20;
  text-align: center;
  user-select: none;

  .title {
    margin-top: 59px;
    margin-bottom: 30px;
    text-align: center;
    font-size: 24px;
    color: #fff;
  }

  .account-input,
  .password-input {
    position: relative;
    margin: 0 auto;
    width: 356px;
    height: 52px;
    background: url('@/assets/images/login/login_input.png') no-repeat center
      center;
    background-size: cover;

    .el-input {
      position: absolute;
      top: 2px;
      left: 70px;
      width: 250px;
      height: 48px;
      border: 0;
      font-size: 16px !important;

      // 去掉el-input的边框
      // 穿透,里面的input背景透明,可以看到外面的背景
      :deep(.el-input__wrapper) {
        background-color: transparent;
        box-shadow: 0 0 0 0px
          var(--el-input-border-color, var(--el-border-color)) inset;

        .el-input__inner {
          font-size: 16px !important;
          color: #fff;
        }
      }
    }

    img {
      position: absolute;
      top: 14px;
      left: 20px;
      width: 26px;
      height: 26px;
    }

    .line {
      position: absolute;
      top: 14px;
      left: 60px;
      width: 1px;
      height: 26px;
      background: #00eaff;
    }
  }

  .password-input {
    margin-top: 41px;
  }

  .validate-input {
    position: relative;
    margin: 0 auto;
    margin-top: 16px;
    width: 356px;
    height: 52px;

    .el-input {
      position: absolute;
      top: 10px;
      left: 30px;
      width: 250px;
      height: 48px;
      border: 0;
      font-size: 16px;

      // 去掉el-input的边框
      // 穿透,里面的input背景透明,可以看到外面的背景
      :deep(.el-input__wrapper) {
        background-color: transparent;
        box-shadow: 0 0 0 0px
          var(--el-input-border-color, var(--el-border-color)) inset;

        .el-input__inner {
          color: #fff;
        }
      }

      // placeholder的颜色浅色
      :deep(input::-webkit-input-placeholder) {
        color: #00eaff;
      }
    }

    .img-div {
      position: absolute;
      top: 12px;
      right: 20px;
      width: 110px;
      height: 42px;
      cursor: pointer;
      user-select: none;
      // background: rgba(255, 255, 255,0.7);
      opacity: 0.8;
      filter: invert(100%);

      // filter: Alpha(opacity=30);
      // 通过css,让图片变蓝
      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .el-button {
    margin-top: 19px;
    background-color: #084de9;
    width: 356px;
    height: 52px;
    border: 0;
    border-radius: 0;
    font-size: 20px;
    letter-spacing: 5px;
    // 按钮的左上和右下切除
    clip-path: polygon(
      15px 0,
      100% 0,
      100% 15px,
      100% calc(100% - 15px),
      calc(100% - 15px) 100%,
      0 100%,
      0 calc(100% - 15px),
      0 15px
    );
  }
}
</style>
